package com.spring.consumebackground.web.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.spring.cardapi.web.service.CardApiService;
import com.spring.consumebackground.web.dao.ConsumeBackgroundMapper;
import com.spring.consumebackground.web.model.Card2;
import com.spring.consumebackground.web.model.Product;
import com.spring.consumebackground.web.service.ConsumeBackgroundService;
import com.spring.membercardapi.web.model.Card;
import com.spring.security.core.context.JedisCont;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.web.dao.JedisCache;
import com.spring.security.web.iputil.HttpClientUtils;
import com.spring.security.web.model.BaseResult;
import com.spring.tools.MyTools;
import com.spring.tools.Url;
import com.sso.api.web.dao.FamilyMemberMapper;
import com.sso.api.web.dao.SsoMapper;
import com.sso.api.web.model.FamilyMember;
import com.sso.api.web.model.SsoUser;
import com.spring.common.web.dao.*;
import com.spring.common.web.model.*;

@Service
public class ConsumeBackgroundServiceImpl implements ConsumeBackgroundService{
	@Resource
	private ConsumeBackgroundMapper consumeBackgroundMapper;
	
	@Resource
	private SsoMapper ssoMapper;
	
    @Resource
    private JedisCache jedisCache;
    
    @Resource
    private  CardApiService cardApiService;
    
    @Resource
    private CustomeerAssistMapper customeerAssistMapper;
    
    @Resource
    private CareClassAppointmentMapper careClassAppointmentMapper;
    
    @Resource
    private FamilyMemberMapper familyMemberMapper;
	

	
	//获取会员卡内容接口
	@Override
	public Map<String, Object> getMemberCardDetail(String card_number,String phone) throws Exception{
		Map<String, Object> m = new HashMap<String, Object>();
		if(card_number!=null&&card_number.equals("")){
			card_number=null;
		}
		if(phone!=null&&phone.equals("")){
			phone=null;
		}

		if(card_number==null&&phone!=null){
			card_number=ssoMapper.getCardNumberByPhone(phone);
			if(card_number==null){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "手机号无效");
				return m;
			}
			
		}
	
		HashMap<String, Object> hmc=MyTools.checkIsNotNull(card_number);
		if(hmc!=null){
			return hmc;
		}
		
		HashMap<String, Object> hm5=new HashMap<String, Object>();
		
		hm5.put("card_number", card_number);
		
		int count=ssoMapper.getMemberIsValid(hm5);
		if(count==0){
			
			String real_card_number=jedisCache.get(card_number);
			if(real_card_number==null||real_card_number.equals("")){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "卡无效");
				return m;
			}else{
				card_number=real_card_number;
			}
		}
				
			List<HashMap> hm2=consumeBackgroundMapper.getMemberCard(card_number);			
			HashMap<String, Object> r=new HashMap<String, Object>();
//			
			if(hm2.size()>0){
				HashMap<String, Object> p2=new HashMap<String, Object>();
				p2.put("card_number", card_number);			
				r=ssoMapper.getUserByCardNumber(p2);
		}		
			
			String cUserID=MyTools.ObjectToString(r.get("c_user_id"));
			
			List<CustomeerAssist> customeerAssist = customeerAssistMapper.selectByUserID(cUserID);
			

			List<Card2> list = consumeBackgroundMapper.getMemberCardDetail(card_number);		
			List<HashMap> hm = consumeBackgroundMapper.getRechargeCardDetail(card_number);
	
			m.put(ApplicationUtils.DATASET, list);
			m.put("user", r);
			m.put("rechargeCard", hm);
			m.put("memberCard", hm2);
			m.put("customeerAssist", customeerAssist);

			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "取数成功");

		
		return m;
	}


	
	@Override
	public Map<String, Object> getRechargeCardDetail(String card_number)
			throws Exception {
		Map<String, Object> m = new HashMap();

		HashMap hmc = MyTools.checkIsNotNull(card_number);
		if (hmc != null) {
			return hmc;
		}

		List<HashMap> hm = consumeBackgroundMapper.getRechargeCardDetail(card_number);

		System.out.println(hm.toString());

		m.put(ApplicationUtils.DATASET, hm);
		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "取数成功");

		return m;
	}
	
	
	@Override
	public HashMap<String, Object> getProductList(String businessTypeCode,String page, String pageSize,
			String kids_park_id, String code, String name, String deptID)
			throws Exception {
		Map<String, Object> m = new HashMap<String, Object>();
		HashMap<String, Object> ret = new HashMap<String, Object>();

		HashMap<String, Object> hmc = MyTools.checkIsNotNull(kids_park_id, deptID);
		if (hmc != null) {
			return null;
		}

		HashMap<String, Object> hmp = MyTools.pageIndexToSkip(pageSize, page, null, null);
		hmp.put("deptID", deptID);
		hmp.put("kids_park_id", kids_park_id);
		hmp.put("code", code);
		hmp.put("name", name);
		hmp.put("businessTypeCode", businessTypeCode);


		
		System.out.println(hmp.toString());
		
		System.out.println(Integer.valueOf(page)+""+Integer.valueOf(pageSize));
		
	//	PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(pageSize));

		List<Product> hm = consumeBackgroundMapper.getProductList(hmp);
		int count=consumeBackgroundMapper.getProductListCount(hmp);
	//	PageInfo pageObj = new PageInfo(hm);
		ret.put("total", count);
		ret.put("data", hm);

		return ret;

	}
	
			//产生订单
			@Override
			public Map<String, Object> checkOut(String assistID,String assistName,String orderID,String c_user_id,String phone ,String kids_park_id,String total_amount, String payment_amount, String desc, 
					String card_number, String order_detail, String order_payment,int isNeedUpdatePoint,String point_source_code,String point_desc,String cashierID,String cashierName) throws Exception{
				Map<String, Object> m = new HashMap<String, Object>();
				
				int isOldOrder=0;
				if(orderID!=null){
					isOldOrder=1;
				}
				
				if(phone!=null){
					if(phone.equals("")){
						phone=null;
					}
				}
				
				if(card_number!=null){
				if(card_number.equals("")){
					card_number=null;
				}
				}
				
				HashMap<String, Object> hmc=MyTools.checkIsNotNull(total_amount,payment_amount,desc,order_detail);
				if(hmc!=null){
					//return hmc;
				}

				//手机卡号只用一个
				if(phone!=null&&card_number!=null){
					phone=null;
				}
				
				if(c_user_id==null){
				HashMap<String,Object> hm5=new HashMap<String,Object>();
				
				hm5.put("card_number", card_number);
				hm5.put("phone", phone);
				
				int count=ssoMapper.getMemberIsValid(hm5);
				if(count==0){
					//验证是否是二维码
					
					String real_card_number=jedisCache.get(card_number);
					if(real_card_number==null||real_card_number.equals("")){
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "卡无效或者手机号无效");
						return m;
					}else{
						card_number=real_card_number;
					}				

				}
				}
				
				BigDecimal payment_amounts=new BigDecimal(0);
				//验证支付金额是否等于总金额
				
				if(order_payment!=null){
				BigDecimal tolalAmountc=new BigDecimal(0);
			
				JSONArray order_paymentjson = JSONArray.fromObject(order_payment);
				// 读取金额
				for (int i = 0; i < order_paymentjson.size(); i++) {
					JSONObject jsonObject = order_paymentjson.getJSONObject(i);
					BigDecimal amountf= new BigDecimal(String.valueOf(jsonObject.get("amount"))); 
					
					BigDecimal paymentAmount=new BigDecimal(0);
					if(MyTools.ObjectToString(jsonObject.get("totalAmount"))==null){
						paymentAmount=amountf;
					}else{
						paymentAmount= new BigDecimal(String.valueOf(jsonObject.get("totalAmount"))); 
					}
					
		
					System.out.println("金额amountf"+amountf);
					
					tolalAmountc=tolalAmountc.add(amountf);
					payment_amounts=paymentAmount.add(payment_amounts);
					}
				}

				int isNeedRegistration=0;
				if(order_detail!=null){
				//验证详细表中数额是否等于总金额
				BigDecimal should_paytemp=new BigDecimal(0);
				JSONArray should_payjson = JSONArray.fromObject(order_detail);
				String[] orderProductList=new String[should_payjson.size()];
				if(should_payjson.size()!=0){
				// 读取金额
					
				for (int i = 0; i < should_payjson.size(); i++) {
					
					JSONObject jsonObject = should_payjson.getJSONObject(i);
					if(jsonObject.get("membercard_id")==null){
					BigDecimal amountf= new BigDecimal(String.valueOf(jsonObject.get("amount"))); 
				
					System.out.println("add"+amountf);
						
					should_paytemp=should_paytemp.add(amountf);
					}
					orderProductList[i]=MyTools.ObjectToString((jsonObject.get("order_product_kids_park_id")));
					}
					
					//判断是否需要签到
					HashMap<String,Object> hmnx=new HashMap<String,Object>();
					hmnx.put("idList", orderProductList);	
					
					//cxvvvvvvvvvvvvvvvvv
					
					int isNeedRegistrationt=consumeBackgroundMapper.getIsNeedRegistration(hmnx);
					if(isNeedRegistrationt>0){
						isNeedRegistration=1;
					}	
				}
				
				}
				String orderNumber=MyTools.getOrderNumber();
				
				String uuid=ApplicationUtils.randomUUID();
				
				if(orderID==null){
					
				
				//用于产生订单的hashmap
				HashMap<String,Object> orderhm=new HashMap<String,Object>();
				orderhm.put("total_amount", total_amount);
				orderhm.put("payment_amount", payment_amounts.toString());
				orderhm.put("desc", desc);
				if(desc!=null&&desc.equals("托班")){
					isNeedRegistration=1;
				}
				orderhm.put("card_number", card_number);
				orderhm.put("kids_park_id", kids_park_id);
				orderhm.put("uuid", uuid);
				orderhm.put("orderNumber", orderNumber);
				orderhm.put("cashierID", cashierID);
				orderhm.put("cashierName", cashierName);
				orderhm.put("isNeedRegistration", isNeedRegistration);	
				orderhm.put("assistID", assistID);
				orderhm.put("assistName", assistName);
				
				//String c_user_id=null;
				if(c_user_id==null){
				//根据手机号来获取用户id
				if(phone!=null){
					HashMap<String,Object> hmpp=new HashMap<String,Object>();
					hmpp.put("phone", phone);
					c_user_id=ssoMapper.getIDByPhone(hmpp);
						
				}
				
				//得到用户id 根据card_number
				if(card_number!=null){					
					c_user_id=	ssoMapper.getIDsByCardNumber(orderhm);
					}
				}
				 
				 if(c_user_id!=null){
						orderhm.put("c_user_id", c_user_id);				
						String real_name=ssoMapper.selectRealNameByID(c_user_id);
						orderhm.put("real_name", real_name);
				 }

				
				int effect= consumeBackgroundMapper.createOrder(orderhm);
				if(effect!=1){
					throw new Exception();
				}
				
				}else{
					uuid=orderID;
				}
				//插入循环order_detail表
				
				List tousonglist=new ArrayList();
				
				long stime=System.currentTimeMillis()/1000;
				
				SsoUser ssoUser=ssoMapper.getUserByID(c_user_id);				
				
				if(order_detail!=null){
					//验证详细表中数额是否等于总金额

					JSONArray order_detailjson = JSONArray.fromObject(order_detail);
					

					// 读取金额
					for (int i = 0; i < order_detailjson.size(); i++) {
						JSONObject jsonObject = order_detailjson.getJSONObject(i);
						
						//验证是否是会员卡
						
						HashMap<String,Object> tuisonghm=new HashMap<String,Object>();
												
						String isAmount="1";
						String package_detail_id=(String)jsonObject.get("package_detail_id");
						if(package_detail_id!=null){
							isAmount="0";
						}
					//	c_user_id		
						
						//用于产生订单详细的hashmap
						HashMap<String,Object> orderDetailhm=new HashMap<String,Object>();
						orderDetailhm.put("uuid", uuid);
						orderDetailhm.put("business_type_code", jsonObject.get("business_type_code"));
						orderDetailhm.put("unit_code", jsonObject.get("unit_code"));
						orderDetailhm.put("amount", jsonObject.get("amount"));
						orderDetailhm.put("quantity", jsonObject.get("quantity"));
						orderDetailhm.put("order_product_kids_parkID", jsonObject.get("order_product_kids_park_id"));
						orderDetailhm.put("remark", MyTools.ObjectToString(jsonObject.get("remark")));
						
						
						orderDetailhm.put("card_number", jsonObject.get("card_number"));
						if(ssoUser!=null){
							orderDetailhm.put("card_out_number", ssoUser.getCard_out_number());
						}
						
						orderDetailhm.put("package_detailID", jsonObject.get("package_detail_id"));
						orderDetailhm.put("card_detail_id", jsonObject.get("card_detail_id"));
						orderDetailhm.put("isAmount", isAmount);
						orderDetailhm.put("membercardID", jsonObject.get("membercard_id"));
						
						String productName=consumeBackgroundMapper.
								getNameByOrderProductKidsParkID(MyTools.ObjectToString(jsonObject.get("order_product_kids_park_id")));
						
						tuisonghm.put("id", ApplicationUtils.randomUUID());
						tuisonghm.put("title", productName);
						tuisonghm.put("number", MyTools.ObjectToString(jsonObject.get("quantity")));
						tuisonghm.put("price", MyTools.ObjectToString(jsonObject.get("amount")));
						tuisonghm.put("timestamp",stime );
						
						tousonglist.add(tuisonghm);
						
						System.out.println(orderDetailhm.toString());
						
						//验证会员卡
						if(isAmount.equals("0")){
							BigDecimal remain=consumeBackgroundMapper.getMemberCardRemain(orderDetailhm);
							if(remain.compareTo(new BigDecimal(String.valueOf(jsonObject.get("quantity"))))==-1){
								m.put(ApplicationUtils.STATUS, "0");
								m.put(ApplicationUtils.MSG, "会员卡余额不足");
								return m;
							}
														
							int effect3=consumeBackgroundMapper.updateMemberCardRemain(orderDetailhm);
							if(effect3!=1){
								throw new Exception();
								}							
						}
						String remainQuantity=MyTools.ObjectToString(jsonObject.get("remainQuantity"));
						if(remainQuantity!=null&&!remainQuantity.equals("--")){
							
							HashMap<String,Object> hmy=new HashMap<String,Object>();							
							hmy.put("order_product_kids_parkID", jsonObject.get("order_product_kids_park_id"));
							hmy.put("quantity", jsonObject.get("quantity"));
							
							int effectn= consumeBackgroundMapper.updateRemainQuantity(hmy);

						}
						
						int effect2=consumeBackgroundMapper.createOrderDetail(orderDetailhm);
						if(effect2!=1){
							throw new Exception();
							}									
						}		
					
				
					}
					
					//循环生成支付详细
					
//					System.out.println("order_payment"+order_payment);
					//if(orderID==null){
						
				    BigDecimal useAmount=new BigDecimal("0");
					JSONArray order_paymentjson = JSONArray.fromObject(order_payment);
					
					for (int i = 0; i < order_paymentjson.size(); i++) {
						JSONObject jsonObject = order_paymentjson.getJSONObject(i);
						
						//验证是否是会员卡

						//用于产生订单详细的hashmap
						HashMap<String, Object> orderPaymenthm=new HashMap<String, Object>();
						orderPaymenthm.put("uuid", uuid);
						orderPaymenthm.put("payment_way_code", jsonObject.get("payment_way_code"));
						//jsonObject.get("amount"));						
						
						orderPaymenthm.put("rechargecardID", MyTools.ObjectToString(jsonObject.get("rechargecard_id")));
						orderPaymenthm.put("card_number", MyTools.ObjectToString(jsonObject.get("card_number")));				
						
						String temppwc=String.valueOf(jsonObject.get("payment_way_code"));
						
						BigDecimal a2=new BigDecimal(String.valueOf(jsonObject.get("amount")));
						
						BigDecimal totalAmount2=a2;
						if(MyTools.ObjectToString(jsonObject.get("totalAmount"))!=null){
							totalAmount2=new BigDecimal(String.valueOf(jsonObject.get("totalAmount")));
						}
						
						
						orderPaymenthm.put("total_amount", totalAmount2);
						orderPaymenthm.put("amount",totalAmount2);
						
						
						
						if(temppwc.equals("2")){
							
	
							HashMap<String, Object> rechargecard=consumeBackgroundMapper.getRechargecardDetailByCardNumber(orderPaymenthm);
							
							BigDecimal a1=(BigDecimal)rechargecard.get("balance");
							
							//discount_rate
							BigDecimal discount_rate=(BigDecimal)rechargecard.get("discount_rate");
							
							//总金额
							BigDecimal amo=new BigDecimal(String.valueOf(jsonObject.get("amount")));
							BigDecimal totalAmount=null;
							if(MyTools.ObjectToString(jsonObject.get("totalAmount"))==null){
								totalAmount=amo;
							}else{
								totalAmount=new BigDecimal(String.valueOf(jsonObject.get("totalAmount")));
							}							
							
							BigDecimal famount=totalAmount;
							//BigDecimal famount= discount_rate.multiply(amo);
							
							orderPaymenthm.put("total_amount", amo);
							orderPaymenthm.put("amount", famount);
							
							
							if(a1.compareTo(famount)==-1){
								m.put(ApplicationUtils.STATUS, "0");
								m.put(ApplicationUtils.MSG, "充值卡余额不足");
								return m;
							}
							int effect5=consumeBackgroundMapper.updateRechargeCardRemain(orderPaymenthm);
							
							//useAmount=useAmount.add(totalAmount.multiply(discount_rate));
							useAmount = useAmount.add(totalAmount);
							
							if(effect5!=1){
								throw new Exception();
								}
							
						}
						//除了购买会员卡充值卡不调用该方法
						if((!temppwc.equals("2"))&&isNeedUpdatePoint==1&&c_user_id!=null){

							if(point_source_code==null){
								point_source_code="5";
							}
							if(point_desc==null){
								point_desc="现金购买商品";
							}
							cardApiService.updatePoint(c_user_id, point_source_code, a2.divide(new BigDecimal(10)).toString(), "1", point_desc);
						}	
						
						if(isOldOrder==1){
							consumeBackgroundMapper.updateOrderAmount(orderPaymenthm);
						}						
						int effect4=consumeBackgroundMapper.createOrderPayment(orderPaymenthm);
						if(effect4!=1){
							throw new Exception();
							}
						//只有刷过卡的才插流水表
						if(jsonObject.get("card_number")!=null){
						int effect5= consumeBackgroundMapper.createOrderJournal(orderPaymenthm);
						if(effect5!=1){
							throw new Exception();
							}
						}
					}
				//	}
					//推送消息
					HashMap<String, Object> tousonglistf=new HashMap<String, Object>();
					
					tousonglistf.put("id", uuid);
					tousonglistf.put("message", "消费提醒您在蒂芭卜产生了一个订单请查看");
					tousonglistf.put("type", 3);
					tousonglistf.put("createTime", stime);
					tousonglistf.put("entity", tousonglist);

					JSONObject tjson=JSONObject.fromObject(tousonglistf);
					
					HashMap<String,Object> hmt=new HashMap<String,Object>();
					hmt.put("type", 3);
					
					JSONObject jst=JSONObject.fromObject(hmt);
					
					//String fjson=tjson.toString();
					
				//	System.out.println(fjson);
					
					HashMap<String,Object> hmx=new HashMap<String,Object>();
					hmx.put("c_user_ids", c_user_id);
					
					hmx.put("title", "消费提醒");
					hmx.put("msg", "消费提醒");
					hmx.put("jsonStr", jst.toString());					
					
					
					System.out.println(hmx.toString());
					if(c_user_id!=null&&!c_user_id.equals("")){
						String json = HttpClientUtils.httpPost(Url.tuisong,hmx);
						System.out.println("json"+json);
					}
	
					// String s=HttpRequest.sendGet("http://localhost:6144/Home/RequestString", "key=123&v=456");					
					
					String phonen="";
					String wx_point="";
					String balance="";
					if(ssoUser!=null){
						phonen=ssoUser.getPhone();
						wx_point=ssoUser.getWx_point();
						balance=consumeBackgroundMapper.getUserBalance(c_user_id);						
					}
				
					HashMap<String,Object> hmr=new HashMap<String,Object>();
					hmr.put("orderID", uuid);
					hmr.put("orderNumber", orderNumber);
					hmr.put("phone", phonen);
					hmr.put("wx_point", wx_point);
					hmr.put("balance", balance);
					hmr.put("useAmount", useAmount);
					
					if(card_number!=null){
						String card_out_number=ssoMapper.getCardOutNumberByCardNumber(card_number);
						hmr.put("card_out_number", card_out_number);
					}
															
					m.put(ApplicationUtils.DATASET, hmr);
					m.put(ApplicationUtils.STATUS, "1");
					m.put(ApplicationUtils.MSG, "支付成功");
		
				return m;
			}
			//课程签到
			@Override//String user_phone
			public Map<String, Object>  courseSignIn(String card_number, String phone, String course_open_detailID,String workID,String workName) throws Exception{
				Map<String, Object> m = new HashMap();
				
				if(card_number!=null&&card_number.equals("")){
					card_number=null;
				}
				
				if(phone!=null&&phone.equals("")){
					phone=null;
				}
				
				HashMap hmc=MyTools.checkIsNotNull(course_open_detailID);
				if(hmc!=null){
					return hmc;
				}
				if(card_number==null&&phone==null){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "手机卡号必须填一个");
					return m;
				}	
				
//				if(card_number!=null&&user_phone!=null){
//					m.put(ApplicationUtils.STATUS, "0");
//					m.put(ApplicationUtils.MSG, "userPhone和card_number不能同时使用");
//					return m;
//				}
					if(phone!=null&&card_number==null){
						card_number=ssoMapper.getCardNumberByPhone(phone);
					}
					
			
					HashMap<String, Object> hm=new HashMap<String, Object>();
					//hm.put("phone", phone);
					hm.put("card_number", card_number);
					hm.put("course_open_detailID", course_open_detailID);
					//使用手机号的情况(充值卡或者手机没有卡)
					String payment_way="";
					
				
					//验证支付方式
//					if(user_phone!=null){
//						payment_way="3";
//					}else
					List<HashMap<String,Object>> hmm= consumeBackgroundMapper.CourseSignGetMemberCard(hm);
					List<HashMap<String,Object>> hmr= consumeBackgroundMapper.getRechargeFAamount(hm);
					
					
					if(hmm.size()>0){						
						payment_way="1";
					}else if(consumeBackgroundMapper.checkRechargecard(hm)>0){
						
						payment_way="2";
						
					}else{
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "卡号无效或内容不足以支付");
						return m;
					}
					
					
				//	String course_appointmentID="";
				//	String idlist=ssoMapper.getIDsByCardNumber(hm);
					
					List<HashMap> idlist=ssoMapper.getIDsByPhone(hm);
					
					//String c_user_id=ssoMapper.getIDsByCardNumber(hm);
					
					hm.put("userList", idlist);
				//	hm.put("c_user_id", c_user_id);
					if(idlist.size()==0){
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "未能查找到用户");
						return m;
					}
				
					String[] course_appointmentIDs=consumeBackgroundMapper.getCourseAppointmentID(hm);
		
					if(course_appointmentIDs.length<1){
						String[] attendedIDs=consumeBackgroundMapper.getAttendedCourseAppointmentID(hm);
						
						if(attendedIDs.length>0){
							m.put(ApplicationUtils.STATUS, "0");
							m.put(ApplicationUtils.MSG, "该用户已经签到完成");
							return m;
						}
						
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "该用户没有预约");
						return m;
					}
					
					String course_appointmentID=course_appointmentIDs[0];
//					
//					//手机充值卡得到预约号
//					
//					if(phone!=null){
//						
//						HashMap<String, Object> hmr1= consumeBackgroundMapper.getAppointmentByPhone(hm);
//						//修改过
//						if(hmr1==null){
//							m.put(ApplicationUtils.STATUS, "0");
//							m.put(ApplicationUtils.MSG, "该手机没有预约");
//							return m;
//						}
//						course_appointmentID=(String)hmr1.get("id");
//						//payment_way="2";
//						
//					}
					
					
					//会员卡得到预约号
//					if(payment_way.equals("1")){
//						
//						HashMap<String, Object> hmr1= consumeBackgroundMapper.getAppointmentByMemberCard(hm);
//						if(hmr1==null){
//							m.put(ApplicationUtils.STATUS, "0");
//							m.put(ApplicationUtils.MSG, "该卡没有预约");
//							return m;
//						}
//						course_appointmentID=(String)hmr1.get("id");
//						//payment_way="1";
//						
//					}
					
					hm.put("course_appointmentID", course_appointmentID);
					
					
					BigDecimal should_pay=new BigDecimal("0");
					BigDecimal actually_paid=new BigDecimal("0");
					String desc="早教";
					card_number=card_number;
					ArrayList order_detail=new ArrayList();
					ArrayList order_payment=new ArrayList();
					String kids_parkID="";

					
					//会员卡支付
					if(payment_way.equals("1")){
						
						List<HashMap<String, Object>> list4=consumeBackgroundMapper.CourseSignGetMemberCard(hm);
						HashMap<String, Object> hmr4=list4.get(0);
//						
//						if(hmr4==null){
//							payment_way="2";
//							
//						}else if(((BigDecimal)hmr4.get("remain_quantity")).compareTo(new BigDecimal(1))<0){
//							payment_way="2";
//						}
						
//						if(payment_way.equals("2")){
//							//使用会员卡虚拟充值卡
//							HashMap<String, Object> hmr5=consumeBackgroundMapper.CourseSignGetRechargecardByMemberCard(hm);
//							//使用虚拟卡卡号覆盖初始卡号
//							hm.put("card_number", hmr5.get("card_number"));
//														
//							HashMap<String, Object> hmr2=consumeBackgroundMapper.getOrderProduct(hm);
//							//充值卡得到卡内容
//							HashMap<String, Object> hmr3=consumeBackgroundMapper.CourseSignGetRechargecard(hm);
//							
//							String amount=String.valueOf(hmr2.get("unitPrice"));
//							
//							should_pay=amount;
//							actually_paid=amount;
//							kids_parkID=String.valueOf(hmr2.get("kids_parkID"));
//							card_number=String.valueOf(hmr3.get("card_number"));
//							
//							HashMap order_detailhm=new HashMap();
//							order_detailhm.put("business_type_code", "1002");
//							order_detailhm.put("unit_code", "5");
//							order_detailhm.put("amount", amount);
//							order_detailhm.put("quantity", 1);
//							order_detailhm.put("order_product_kids_park_id", hmr2.get("order_product_kids_park_id"));
//							
//							order_detail.add(order_detailhm);
//							JSONArray json=JSONArray.fromObject(order_detail);
//							System.out.println(json.toString());
//							
//							HashMap order_paymenthm=new HashMap();
//							order_paymenthm.put("payment_way_code", payment_way);
//							order_paymenthm.put("amount", amount);
//							order_paymenthm.put("card_number", hmr3.get("card_number"));
//							order_paymenthm.put("rechargecard_id", hmr3.get("rechargecard_id"));
//							
//							order_payment.add(order_paymenthm);
//							JSONArray json2=JSONArray.fromObject(order_payment);
//							System.out.println(json2.toString());
//						
//							
//						}else{
							//使用会员卡支付 生成order_detail
							kids_parkID=(String)hmr4.get("kids_parkID");
							
							HashMap order_detailhm=new HashMap();
							order_detailhm.put("business_type_code", "1002");
							order_detailhm.put("unit_code", "6");
							order_detailhm.put("quantity", "1");
							order_detailhm.put("membercard_id",hmr4.get("membercard_id"));
							order_detailhm.put("order_product_kids_park_id",hmr4.get("order_product_kids_park_id"));
							order_detailhm.put("card_number",hmr4.get("order_product_kids_park_id"));
							order_detailhm.put("package_detail_id",hmr4.get("package_detail_id"));
							order_detailhm.put("card_detail_id",hmr4.get("card_detail_id"));
							
							order_detail.add(order_detailhm);
							JSONArray json=JSONArray.fromObject(order_detail);
							System.out.println(json.toString());
							
							//使用会员卡支付 生成order_payment 不用
							
							
							
				//		}
						
						
						
					}else
					
					//充值卡
					if(payment_way.equals("2")){
					//充值卡得到商品内容
					HashMap<String, Object> hmr2=consumeBackgroundMapper.getOrderProduct(hm);
					//充值卡得到卡内容
				//	HashMap<String, Object> hmr3=consumeBackgroundMapper.CourseSignGetRechargecard(hm);
					
					String amount=String.valueOf(hmr2.get("unitPrice"));
					
					
					//discount_rate
					BigDecimal discount_rate=(BigDecimal)hmr.get(0).get("discount_rate");
					
					String isDiscount=MyTools.ObjectToString(hmr2.get("isDiscount"));
					BigDecimal finalAmount=null;
					if(isDiscount.equals("1")){
						finalAmount=new BigDecimal(amount).multiply(discount_rate);
					}else{
						finalAmount=new  BigDecimal(amount);
					}
					
					
					//总金额
					//BigDecimal amo=new BigDecimal(String.valueOf(jsonObject.get("amount")));
					
					//BigDecimal totalAmount=new BigDecimal(String.valueOf(jsonObject.get("totalAmount")));
					
				//	BigDecimal famount=totalAmount;
					//BigDecimal famount= discount_rate.multiply(amo);
					
			
					
					should_pay=finalAmount;
					actually_paid=finalAmount;
					
					//should_pay=amount;
					//actually_paid=amount;
					kids_parkID=String.valueOf(hmr2.get("kids_parkID"));
					//card_number=String.valueOf(hmr3.get("card_number"));
					
					HashMap order_detailhm=new HashMap();
					order_detailhm.put("business_type_code", "1002");
					order_detailhm.put("unit_code", "5");
					order_detailhm.put("amount", finalAmount.toString());
					order_detailhm.put("quantity", 1);
					order_detailhm.put("order_product_kids_park_id", hmr2.get("order_product_kids_park_id"));
					
					order_detail.add(order_detailhm);
					JSONArray json=JSONArray.fromObject(order_detail);
					System.out.println(json.toString());
					
				//	String card_number=hmr.get(0).get("card_number");
					String rechargecard_id=MyTools.ObjectToString(hmr.get(0).get("rechargecardID"));
					
					
					HashMap order_paymenthm=new HashMap();
					order_paymenthm.put("payment_way_code", payment_way);
					order_paymenthm.put("amount", finalAmount.toString());
					order_paymenthm.put("totalAmount", finalAmount.toString());
				//	order_paymenthm.put("card_number",hmr.get(0).get("card_number"));
					order_paymenthm.put("rechargecard_id",rechargecard_id );
					

			//		hmr.get(0).get("rechargecard_id");
					
					order_payment.add(order_paymenthm);
					JSONArray json2=JSONArray.fromObject(order_payment);
					System.out.println(json2.toString());
					
					
					}
					
//					else
//					
//					//现金
//					if(payment_way.equals("3")){
//						String phonep=user_phone;
//						
//						HashMap<String, Object> hmr2=consumeBackgroundMapper.getOrderProduct(hm);						
//						String amount=String.valueOf(hmr2.get("unitPrice"));						
//						should_pay=amount;
//						actually_paid=amount;
//						kids_parkID=String.valueOf(hmr2.get("kids_parkID"));
//						
//						HashMap order_detailhm=new HashMap();
//						order_detailhm.put("business_type_code", "1002");
//						order_detailhm.put("unit_code", "5");
//						order_detailhm.put("amount", amount);
//						order_detailhm.put("quantity", 1);
//						order_detailhm.put("order_product_kids_park_id", hmr2.get("order_product_kids_park_id"));
//						
//						order_detail.add(order_detailhm);
//						JSONArray json=JSONArray.fromObject(order_detail);
//						System.out.println(json.toString());
//						
//						
//						
//						HashMap order_paymenthm=new HashMap();
//						order_paymenthm.put("payment_way_code", payment_way);
//						order_paymenthm.put("amount", amount);
//
//						
//						order_payment.add(order_paymenthm);
//						JSONArray json2=JSONArray.fromObject(order_payment);
//						System.out.println(json2.toString());
//						
//						
//						//cardApiService.updatePoint(c_user_id, point_source_code, change_point, change_type_code, desc);
//						
//					}
			
					
					System.out.println(hm.toString());
					
					JSONArray order_detailjson=JSONArray.fromObject(order_detail);
					System.out.println(order_detailjson.toString());
					
					JSONArray order_paymentjson=JSONArray.fromObject(order_payment);
					System.out.println(order_paymentjson.toString());
					
					
					System.out.println(order_detailjson.toString());
					System.out.println(order_paymentjson.toString());
					
					System.out.println(should_pay.toString());
					System.out.println(actually_paid.toString());
					String order_paymentstr="[]";
					
					if(order_paymentjson.size()==0){
						order_paymentstr="[]";
					}else{
						order_paymentstr=order_paymentjson.toString();
					}
					
					//第二个参数本来是user_phone
					Map<String, Object> rmap=this.checkOut(null,null,null,null,null, kids_parkID, should_pay.toString(), actually_paid.toString(), desc, card_number, order_detailjson.toString(), order_paymentstr,1,"5","早教",workID,workName);
					
					if(rmap.get(ApplicationUtils.STATUS).equals("0")){
						return rmap;
					}
					
					Map<String, Object> order=(Map<String, Object>)rmap.get(ApplicationUtils.DATASET);
					String orderID=MyTools.ObjectToString(order.get("orderID"));
					
					hm.put("orderID", orderID);
															
					int effect=consumeBackgroundMapper.updateCourseAppointment(hm);
					if(effect!=1){
						throw new Exception();
					}
					hm.put("appointmentID", course_appointmentID);
										
					m.put(ApplicationUtils.DATASET, hm);
					m.put(ApplicationUtils.STATUS, "1");
					m.put(ApplicationUtils.MSG, "签到成功");

				
				return m;
			}
			
			
			
			@Override
			public Map<String, Object>  courseRewrite(String appointmentID, String specialRequirement, 
					String receiveUserID, String receiveUserName) throws Exception{
					
					HashMap hmc=MyTools.checkIsNotNull(appointmentID,specialRequirement,receiveUserID,receiveUserName);
					if(hmc!=null){
						return hmc;
					}
				
					Map<String, Object> m = new HashMap();
				
					HashMap<String, Object> hm=new HashMap<String, Object>();
					hm.put("appointmentID", appointmentID);
					hm.put("specialRequirement", specialRequirement);
					hm.put("receiveUserID", receiveUserID);
					hm.put("receiveUserName", receiveUserName);
					
					int effect= consumeBackgroundMapper.courseRewrite(hm);
					
					if(effect==0){
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "写入失败");
						return m;
					}
					
					m.put(ApplicationUtils.STATUS, "1");
					m.put(ApplicationUtils.MSG, "写入成功");
					return m;
			}
			
			
			//托班签到

			@Override
			public Map<String, Object>  careClassSignIn(String user_phone,String card_number, String phone,String workID,String workName,String babyID) throws Exception{
				Map<String, Object> m = new HashMap<String, Object>();
				
				if(card_number!=null&&card_number.equals("")){
					card_number=null;
				}
				
				if(phone!=null&&phone.equals("")){
					phone=null;
				}
				
				if(card_number==null&&phone==null){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "手机卡号必须填一个");
					return m;
				}	
				
				if(phone!=null&&card_number==null){
						card_number=ssoMapper.getCardNumberByPhone(phone);
				}
		
					HashMap<String, Object> hm=new HashMap<String, Object>();
					hm.put("phone", phone);
					hm.put("card_number", card_number);
					hm.put("babyID", babyID);				
					
					//使用手机号的情况(充值卡或者手机没有卡)
					
					List<HashMap> idlist=ssoMapper.getIDsByPhone(hm);
					
					if(idlist.size()==0){
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "未能查找到用户");
						return m;
					}
					
					if(babyID==null){
						babyID=(String)((HashMap)idlist.get(0)).get("c_user_id") ;
					}
					
					hm.put("userList", idlist);	
	
					String payment_way="";

					List<HashMap<String,Object>> membercardList= consumeBackgroundMapper.getMembercardCareClassByCardNumber(card_number);

					int count = membercardList.size();
	
					String[] applicationIDs=consumeBackgroundMapper.checkIsAttendCareClass(hm);
					
					if(count==0){
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "卡过期或者余额不足或者套餐已用完");
						return m;
					}
					
					if(count<=applicationIDs.length){
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "已经签到无需再次签到");
						return m;
					}
					
					if(count>0){
						payment_way="1";
					}else if(count<1&&consumeBackgroundMapper.checkRechargecard(hm)>0){
						payment_way="2";
					}else{
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "卡号无效或内容不足以支付");
						return m;
					}
					
					if(idlist.size()<=applicationIDs.length){
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "孩子已签到");
						return m;
					}
	
					HashMap<String,Object> baby = idlist.get(0);

					String real_name=(String) baby.get("real_name");

					BigDecimal should_pay=new BigDecimal("0");
					BigDecimal actually_paid=new BigDecimal("0");
					String desc="托班";
					ArrayList order_detail=new ArrayList();
					ArrayList order_payment=new ArrayList();
					String kids_parkID="";

					//会员卡支付
					if(payment_way.equals("1")){
						
						HashMap<String, Object> hmr4=membercardList.get(0);//consumeBackgroundMapper.careClassSignGetMemberCard(hm);
						
						BigDecimal finalAmount=null;
						String amount=String.valueOf(hmr4.get("unitPrice"));
				
						finalAmount=new  BigDecimal(amount);
					
						should_pay=new  BigDecimal(0);
						actually_paid=new  BigDecimal(0);
						
						kids_parkID=String.valueOf(hmr4.get("kids_parkID"));
		
						HashMap<String,Object> order_detailhm=new HashMap<String,Object>();
						order_detailhm.put("business_type_code", "1001");
						order_detailhm.put("unit_code", "5");
						order_detailhm.put("amount", finalAmount.toString());
								
						order_detailhm.put("quantity", 1);
						order_detailhm.put("order_product_kids_park_id", hmr4.get("order_product_kids_park_id"));
						order_detailhm.put("membercard_id", hmr4.get("membercard_id"));
						order_detailhm.put("card_number", hmr4.get("card_number"));

						order_detail.add(order_detailhm);
						
					}else
				
					//充值卡
					if(payment_way.equals("2")){
					//充值卡得到商品内容
					HashMap<String, Object> hmr2=consumeBackgroundMapper.getCareClassOrderProduct(hm);
					//充值卡得到卡内容     getRechargeFAamount
					List<HashMap<String, Object>> hmr3=consumeBackgroundMapper.getRechargeFAamount(hm);
					
					String rechargecardID=MyTools.ObjectToString(hmr3.get(0).get("rechargecardID"));
					
					BigDecimal discount_rate=new BigDecimal(MyTools.ObjectToString(hmr3.get(0).get("discount_rate")));
					
					String isDiscount=MyTools.ObjectToString(hmr2.get("isDiscount"));
					BigDecimal finalAmount=null;
					String amount=String.valueOf(hmr2.get("unitPrice"));
			
					if(isDiscount.equals("1")){
						finalAmount=new BigDecimal(amount).multiply(discount_rate);
					}else{
						finalAmount=new  BigDecimal(amount);
					}
				
					should_pay=finalAmount;
					actually_paid=finalAmount;
					
					kids_parkID=String.valueOf(hmr2.get("kids_parkID"));
	
					HashMap<String,Object> order_detailhm=new HashMap<String,Object>();
					order_detailhm.put("business_type_code", "1001");
					order_detailhm.put("unit_code", "5");
					order_detailhm.put("amount", finalAmount.toString());
							
					order_detailhm.put("quantity", 1);
					order_detailhm.put("order_product_kids_park_id", hmr2.get("order_product_kids_park_id"));
					
					order_detail.add(order_detailhm);
					JSONArray json=JSONArray.fromObject(order_detail);
					System.out.println(json.toString());
					
					HashMap<String,Object> order_paymenthm=new HashMap<String,Object>();
					order_paymenthm.put("payment_way_code", payment_way);
					order_paymenthm.put("amount", finalAmount.toString());
					order_paymenthm.put("totalAmount", finalAmount.toString());
					order_paymenthm.put("rechargecard_id", rechargecardID);
					
					order_payment.add(order_paymenthm);
					JSONArray json2=JSONArray.fromObject(order_payment);
					}

					JSONArray order_detailjson=JSONArray.fromObject(order_detail);

					
					JSONArray order_paymentjson=JSONArray.fromObject(order_payment);

					System.out.println(order_detailjson.toString());
					System.out.println(order_paymentjson.toString());
					
					
					Map<String, Object> rmap=this.checkOut(null,null,null,null,null, kids_parkID, should_pay.toString(), actually_paid.toString(), desc, card_number, order_detailjson.toString(), order_paymentjson.toString(),1,"5","托班",workID,workName);
					
					if(rmap.get(ApplicationUtils.STATUS).equals("0")){
						return rmap;
					}
					Map<String, Object> order=(Map<String, Object>)rmap.get(ApplicationUtils.DATASET);
					
					String orderID=MyTools.ObjectToString(order.get("orderID"));
					
					String care_class_appointmentID=UUID.randomUUID().toString();
					
					hm.put("id", care_class_appointmentID);
					hm.put("orderID", orderID);

					hm.put("userName", real_name);
					hm.put("cUserId", babyID);
					hm.put("workID", workID);
					hm.put("workName", workName);

					int effect=careClassAppointmentMapper.insert(hm);
					
					if(effect!=1){
						throw new Exception();
					}
					hm.put("appointmentID", care_class_appointmentID);
					
					String className=consumeBackgroundMapper.getCareClassNameByUserID(babyID);
					hm.put("className", className);
					
					m.put(ApplicationUtils.DATASET, hm);					
					m.put(ApplicationUtils.STATUS, "1");
					m.put(ApplicationUtils.MSG, "签到成功");

				
				return m;
			}
			
			
			//托班签退

			@Override
			public Map<String, Object>  careClassSignOff(String user_phone,String card_number, String phone,String babyID) throws Exception{
				Map<String, Object> m = new HashMap<String, Object>();
				
				if(card_number!=null&&card_number.equals("")){
					card_number=null;
				}
				
				if(phone!=null&&phone.equals("")){
					phone=null;
				}

				if(card_number==null&&phone==null){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "手机卡号必须填一个");
					return m;
				}	
	
				if(phone!=null&&card_number==null){
						card_number=ssoMapper.getCardNumberByPhone(phone);
				}		
					HashMap<String, Object> hm=new HashMap<String, Object>();
					hm.put("phone", phone);
					hm.put("card_number", card_number);
					//使用手机号的情况(充值卡或者手机没有卡)
					
/*					List<HashMap> idlist=ssoMapper.getIDsByPhone(hm);
					
					hm.put("userList", idlist);*/					
					hm.put("babyID", babyID);

					String[] AppointmentIDs= consumeBackgroundMapper.getSignOffAppointmentID(hm);
					
					if(AppointmentIDs.length==0){
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "该卡没有签到过");
						return m;
					}
					
					int effect=consumeBackgroundMapper.signOffAppointment(AppointmentIDs[0]);
					
					if(effect==0){
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "签退失败");
						return m;
					}
					
					m.put(ApplicationUtils.STATUS, "1");
					m.put(ApplicationUtils.MSG, "签退成功");
					return m;
			}
			
			
			
			@Override
			public Map<String, Object>  careClassRewrite(String appointmentID, String specialRequirement, 
					String receiveUserID, String receiveUserName) throws Exception{
					
					HashMap hmc=MyTools.checkIsNotNull(appointmentID,specialRequirement,receiveUserID,receiveUserName);
					if(hmc!=null){
						return hmc;
					}
				
					Map<String, Object> m = new HashMap();
				
					HashMap<String, Object> hm=new HashMap<String, Object>();
					hm.put("appointmentID", appointmentID);
					hm.put("specialRequirement", specialRequirement);
					hm.put("receiveUserID", receiveUserID);
					hm.put("receiveUserName", receiveUserName);
					
					int effect= consumeBackgroundMapper.careClassRewrite(hm);
					
					if(effect==0){
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "写入失败");
						return m;
					}
					
					m.put(ApplicationUtils.STATUS, "1");
					m.put(ApplicationUtils.MSG, "写入成功");
					return m;
			}

		@Override
		public BaseResult delOrder(String orderID) throws Exception{		
			int effect = consumeBackgroundMapper.delOrder(orderID);
			int effect2 = consumeBackgroundMapper.delOrderDetail(orderID);
			int effect3 = consumeBackgroundMapper.delOrderPayment(orderID);
			int effect4 = consumeBackgroundMapper.updateRemain(orderID);
			
			if(effect==0){
				return new BaseResult("0","撤销失败");
			}			
			return new BaseResult("1","撤销成功");
		}	
	
}
